package com.android.test.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.android.test.R;
import com.android.test.R.color;
import com.android.test.model.Subject;
import com.android.test.model.TestRecord;
import com.android.test.util.DataRecordUtil;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SubjectStudyActivity extends Activity {

	private final String TAG = getClass().getSimpleName();
	private final int MSG_WEEK_LEFT_CHANGED = 1;
	private final int MSG_WEEK_RIGHT_CHANGED = 2;
	private final int PAGE_KEYPOINT =0;
	private final int PAGE_SMALLTEST =1;
	private final int PAGE_TESTRESULT =2;
	private final int weekCount = 3;
	private int mCurWeek = 0;
	private LinearLayout llay_for_result;
	private LinearLayout llay_for_tab;
	private RelativeLayout llay_for_result_test;
	private LayoutInflater mLayoutInflater;
	private TextView btn_keypoint;
	private TextView btn_smalltest;
	private TextView btn_submit;
	private TextView btn_retry;
	private TextView btn_toresult;
	private TextView img_to_prev;
	private TextView img_to_next;
	private TextView week_show;
	private TextView txt_test_count;
	private TextView txt_test_wrong_count;
	private TextView txt_test_score;
	private Button btn_wrong_detail;
	private String[] arrayKeypoints;
	private String[] arrayWeeks;
	private String[] arrayAnswersChinese;
	private boolean[] arrayExpanded;
	private List<String> arrayDetails = new ArrayList<String>(0);
	private List<QuestionItem> chineseQuestionList;
	private List<QuestionItem> mWrongList;
	private List<String> mRightAnswerForChinese;
	private int[] weekQuestionCount;
	private ListView list;
	private keypointListAdapter mListAdapter;
	private QuestionAdapter mQuestionAdapter;
	private QuestionResultAdapter mQuestionResultAdapter;
	private int mScreenWidth = -1;
	private int mShowPage = 0;
	private long mTimeTestStart;
	private long mTimeTestEnd;
	private int mScore = 0;

	private int[] weekTestFinished;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mCurWeek = 1;
		getWindow().setFormat(1);
		mScreenWidth = getResources().getDisplayMetrics().widthPixels;
		setContentView(R.layout.activity_subject);
		mLayoutInflater = LayoutInflater.from(this);
		findViews();
		loadData();
		initViews();
		setClickListener();
	}

	private void loadData() {
		String[] tmpArray;
		weekTestFinished = new int[weekCount];
		arrayWeeks = getResources().getStringArray(R.array.weeks);
		arrayKeypoints = getResources()
				.getStringArray(R.array.keypoint_chinese);
		arrayAnswersChinese = getResources().getStringArray(R.array.question_answers);
//		Log.e(TAG,"arrayAnswersChinese count = "+arrayAnswersChinese.length);
		arrayExpanded = new boolean[arrayKeypoints.length];
		tmpArray = getResources().getStringArray(
				R.array.detail_week_first_chinese);
		for (int i = 0; i < tmpArray.length; i++) {
			arrayDetails.add(tmpArray[i]);
		}
		tmpArray = getResources().getStringArray(
				R.array.detail_week_second_chinese);
		for (int i = 0; i < tmpArray.length; i++) {
			arrayDetails.add(tmpArray[i]);
		}
		tmpArray = getResources().getStringArray(
				R.array.detail_week_third_chinese);
		for (int i = 0; i < tmpArray.length; i++) {
			arrayDetails.add(tmpArray[i]);
		}
		readQuestionsFromFile();
	}

	private void readQuestionsFromFile() {
		String encoding_utf8 = "UTF-8";
		String encoding_gb2312 = "GB2312";
		int i = 0;
		if (null == chineseQuestionList) {
			chineseQuestionList = new ArrayList<QuestionItem>();
		}
		InputStream in = getResources().openRawResource(R.raw.question_chinese);
		BufferedReader bufferedReader = null;
		try {
			bufferedReader = new BufferedReader(new InputStreamReader(in,
					encoding_gb2312));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		QuestionItem item;
		weekQuestionCount = new int[weekCount];
		int count = 0;
		try {
			for (String s = bufferedReader.readLine(); s != null;) {
				if (s.equals("第一周")) {
					count = 0;
					s = bufferedReader.readLine();
					continue;
				} else if (s.equals("第二周")) {
					weekQuestionCount[0] = count;
//					Log.e(TAG,"weekQuestionCount[0] = "+weekQuestionCount[0]);
					count = 0;
					s = bufferedReader.readLine();
					continue;
				} else if (s.equals("第三周")) {
					weekQuestionCount[1] = count;
//					Log.e(TAG,"weekQuestionCount[1] = "+weekQuestionCount[1]);
					count = 0;
					s = bufferedReader.readLine();
					continue;
				} else if (s.equals("END:")) {
					weekQuestionCount[2] = count;
//					Log.e(TAG,"weekQuestionCount[2] = "+weekQuestionCount[2]);
					count = 0;
					break;
				} else {
					item = new QuestionItem();
					boolean bChoice = false;
					boolean bBreak = false;
					while (s != null) {
						if (s.indexOf('A') == 0) {
							item.txtCha = s;
							bChoice = true;
						} else if (s.indexOf('B') == 0) {
							item.txtChb = s;
							bChoice = true;
						} else if (s.indexOf('C') == 0) {
							item.txtChc = s;
							bChoice = true;
						} else if (s.indexOf('D') == 0) {
							item.txtChd = s;
							bChoice = true;
						} else if (s.contains("group:")) {
							if (bChoice) {
								bBreak = true;
								bChoice = false;
							} else {
								item.questionGroupDes = s.substring(6);
							}
						} else {
							if (bChoice) {
								bBreak = true;
								bChoice = false;
							} else {
								if (s.contains("第二周") || s.contains("第三周")) {
									bBreak = true;
									bChoice = false;
								} else {
									item.questionDes = s;
								}
							}
						}
						if (bBreak) {
							chineseQuestionList.add(item);
							count++;
							break;
						} else {
							s = bufferedReader.readLine();
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void setExpandedState(boolean flag) {
		for (int i = 0; i < arrayExpanded.length; i++) {
			arrayExpanded[i] = flag;
		}
	}

	private Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_WEEK_LEFT_CHANGED: {
				if (mShowPage == PAGE_KEYPOINT) {
					setExpandedState(true);
					mListAdapter.notifyDataSetChanged();
				} else if (mShowPage == PAGE_SMALLTEST) {
					int pos = 0; 
					for (int i = 1; i < mCurWeek; i++) {
						pos += weekQuestionCount[i - 1];
					}
					mQuestionAdapter.setBasePos(pos);
					mQuestionAdapter.notifyDataSetChanged();
					mTimeTestStart=System.currentTimeMillis();
				} else if(mShowPage==PAGE_TESTRESULT) {
					if (weekTestFinished[mCurWeek - 1] > 0) {
						int pos = 0;
						for (int i = 1; i < mCurWeek; i++) {
							pos += weekQuestionCount[i - 1];
						}
						mQuestionResultAdapter.setBasePos(pos);
						mQuestionResultAdapter.setData(chineseQuestionList);
						mQuestionResultAdapter.setItemCount(weekQuestionCount[mCurWeek-1]);
						mQuestionResultAdapter.notifyDataSetChanged();
						mTimeTestStart=System.currentTimeMillis();
					} else {
						Toast.makeText(SubjectStudyActivity.this,
								R.string.msg_test_not_done, Toast.LENGTH_SHORT)
								.show();
						if (mCurWeek < weekCount) {
							mCurWeek++;
						}
					}
				}
				week_show.setText(arrayWeeks[mCurWeek - 1]);
			}
				break;
			case MSG_WEEK_RIGHT_CHANGED: {
				if (mShowPage == PAGE_KEYPOINT) {
					setExpandedState(true);
					mListAdapter.notifyDataSetChanged();
				} else if (mShowPage == PAGE_SMALLTEST) {
					int pos = 0; 
					for (int i = 1; i < mCurWeek; i++) {
						pos += weekQuestionCount[i - 1];
					}
					mQuestionAdapter.setBasePos(pos);
					mQuestionAdapter.notifyDataSetChanged();
				} else if(mShowPage==PAGE_TESTRESULT) {
					if (weekTestFinished[mCurWeek - 1] > 0) {
						int pos = 0;
						for (int i = 1; i < mCurWeek; i++) {
							pos += weekQuestionCount[i - 1];
						}
						mQuestionResultAdapter.setBasePos(pos);
						mQuestionResultAdapter.setData(chineseQuestionList);
						mQuestionResultAdapter.setItemCount(weekQuestionCount[mCurWeek-1]);
						mQuestionResultAdapter.notifyDataSetChanged();
					} else {
						Toast.makeText(SubjectStudyActivity.this,
								R.string.msg_test_not_done, Toast.LENGTH_SHORT)
								.show();
						if (mCurWeek > 1) {
							mCurWeek--;
						}
					}
				}
				week_show.setText(arrayWeeks[mCurWeek - 1]);
			}
				break;
			}
		}
	};

	private void findViews() {
		// spinner_weeks = (Spinner) findViewById(R.id.weeks_spinner_actionbar);
		// spinner_weeks.setVisibility(View.VISIBLE);
		// spinner_weeks.setBackgroundColor(R.color.list_item_gray);
		llay_for_result = (LinearLayout) findViewById(R.id.llay_for_result);
		llay_for_tab = (LinearLayout) findViewById(R.id.llay_for_tab);
		llay_for_result_test=(RelativeLayout)findViewById(R.id.test_result_layout);
		btn_keypoint = (TextView) findViewById(R.id.btn_keypoint);
		btn_smalltest = (TextView) findViewById(R.id.btn_unittest);
		btn_submit = (TextView) findViewById(R.id.btn_submit);
		btn_retry = (TextView) findViewById(R.id.btn_retry);
		btn_toresult = (TextView) findViewById(R.id.btn_toresult);
		img_to_prev = (TextView) findViewById(R.id.to_prev);
		img_to_next = (TextView) findViewById(R.id.to_next);
		week_show = (TextView) findViewById(R.id.msg_show);
		txt_test_count = (TextView) llay_for_result_test.findViewById(R.id.txt_test_count);
		txt_test_wrong_count = (TextView) llay_for_result_test.findViewById(R.id.txt_wrong_count);
		txt_test_score = (TextView) llay_for_result_test.findViewById(R.id.txt_score);
		btn_wrong_detail = (Button) llay_for_result_test.findViewById(R.id.btn_show_wrong_detail);
		list = (ListView) findViewById(R.id.list_suject);
	}

	private void initViews() {
		btn_keypoint.setBackgroundColor(color.foreground1);
		btn_smalltest.setBackgroundColor(color.foreground2);
		btn_submit.setVisibility(View.GONE);
		week_show.setText(arrayWeeks[0]);
		llay_for_result.setVisibility(View.GONE);
		llay_for_result_test.setVisibility(View.GONE);
		setExpandedState(true);
		mListAdapter = new keypointListAdapter();
		list.setAdapter(mListAdapter);
		list.setDivider(null);
		list.setSelector(R.drawable.list_selector_transparent);
		mQuestionAdapter = new QuestionAdapter(this, chineseQuestionList);
		mQuestionResultAdapter = new QuestionResultAdapter(this,
				chineseQuestionList);
	}

	private void resetChineseQuestions() {
		int basPos = 0;
		for (int i = 1; i < mCurWeek - 1; i++) {
			basPos += weekQuestionCount[i - 1];
		}
		int end = basPos + weekQuestionCount[mCurWeek - 1];
		for (int i = basPos; i < end; i++) {
			chineseQuestionList.get(i).setChecked(false);
			chineseQuestionList.get(i).isRight = false;
		}
	}

	private boolean checkChineseQuestions() {
		int start = 0;
		for (int i = 1; i < mCurWeek - 1; i++) {
			start += weekQuestionCount[i - 1];
		}
		int end = start + weekQuestionCount[mCurWeek - 1];
		for (int i = start; i < end; i++) {
			if (!chineseQuestionList.get(i).getChecked()) {
				return false;
			}
		}
		return true;
	}

	private int getWrongQuestions(){
		int wrongCount = 0;
		int start = 0;
		for (int i = 1; i < mCurWeek - 1; i++) {
			start += weekQuestionCount[i - 1];
		}
		int end = start + weekQuestionCount[mCurWeek - 1];
		if(null==mWrongList){
			mWrongList = new ArrayList<QuestionItem>();
		}
		if(null==mRightAnswerForChinese){
			mRightAnswerForChinese = new ArrayList<String>();
		}
		mRightAnswerForChinese.clear();
		mWrongList.clear();
		for (int i = start; i < end; i++) {
			final QuestionItem item = chineseQuestionList.get(i);
			if(!String.valueOf(item.getChoice()).equals(arrayAnswersChinese[i])){
				wrongCount++;
				item.setChecked(false);
				mWrongList.add(item);
				mRightAnswerForChinese.add(arrayAnswersChinese[i]);
			}else{
				chineseQuestionList.get(i).isRight=true;
			}
		}
		return wrongCount;
	}
	
	private void setClickListener() {
		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
//				Log.e(TAG, "position=" + position + " has been clicked");
				mListAdapter.toggle(position);
			}
		});

		btn_keypoint.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				btn_keypoint.setBackgroundColor(color.foreground2);
				btn_smalltest.setBackgroundColor(color.foreground1);
				btn_submit.setVisibility(View.GONE);
				list.setAdapter(mListAdapter);
				mShowPage = PAGE_KEYPOINT;
				// list.setAdapter(new ArrayAdapter<String>(SubjectStudy.this,
				// android.R.layout.simple_list_item_1, mStrings));
			}
		});

		btn_smalltest.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				btn_smalltest.setBackgroundColor(color.foreground2);
				btn_keypoint.setBackgroundColor(color.foreground1);
				btn_submit.setVisibility(View.VISIBLE);
				// btn_submit.setBackgroundColor(color.background1);
				llay_for_result.setVisibility(View.GONE);
				llay_for_result_test.setVisibility(View.GONE);
				int pos = 0; 
				for (int i = 1; i < mCurWeek; i++) {
					pos += weekQuestionCount[i - 1];
				}
				mQuestionAdapter.setBasePos(pos);
				list.setAdapter(mQuestionAdapter);
				mShowPage = PAGE_SMALLTEST;
				mTimeTestStart=System.currentTimeMillis();
				mScore = 0;
				// list.setAdapter(new ArrayAdapter<String>(
				// SubjectStudyActivity.this,
				// android.R.layout.simple_list_item_1, mStrings1));
			}
		});

		btn_submit.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if (!checkChineseQuestions()) {
					Toast.makeText(SubjectStudyActivity.this,
							R.string.msg_questions_not_finished,
							Toast.LENGTH_SHORT).show();
					return;
				}
				
				mTimeTestEnd=System.currentTimeMillis();
				final int questionCount = weekQuestionCount[mCurWeek - 1];
				txt_test_count.setText(""+questionCount);
				final int wrongCount = getWrongQuestions();
				Log.e(TAG, "WrongCount="+wrongCount);
				txt_test_wrong_count.setText(""+wrongCount);
				mScore = (int) ((questionCount-wrongCount)*100/(float)questionCount);
				txt_test_score.setText(""+mScore+"分");
				btn_wrong_detail.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						mQuestionResultAdapter.setData(mWrongList);
						mQuestionResultAdapter.setRightAnswers(mRightAnswerForChinese);
						mQuestionResultAdapter.setBasePos(0);
						mQuestionResultAdapter.setItemCount(mWrongList.size());
						mQuestionResultAdapter.notifyDataSetChanged();
						mShowPage = PAGE_TESTRESULT;
						llay_for_result_test.setVisibility(View.GONE);
						btn_retry.setVisibility(View.GONE);
						btn_toresult.setVisibility(View.GONE);
					}
				});
				weekTestFinished[mCurWeek - 1] = 1;
				llay_for_tab.setVisibility(View.GONE);
				llay_for_result.setVisibility(View.VISIBLE);
				llay_for_result_test.setVisibility(View.VISIBLE);
				btn_submit.setVisibility(View.GONE);
				btn_retry.setVisibility(View.VISIBLE);
				btn_toresult.setVisibility(View.VISIBLE);
				int pos = 0;
				for (int i = 1; i < mCurWeek; i++) {
					pos += weekQuestionCount[i - 1];
				}
				mQuestionResultAdapter.setBasePos(pos);
				if(null==mRightAnswerForChinese){
					mRightAnswerForChinese = new ArrayList<String>();
				}
				mRightAnswerForChinese.clear();
				for(int i=0;i<arrayAnswersChinese.length;i++){
					mRightAnswerForChinese.add(arrayAnswersChinese[i]);
				}
				mQuestionResultAdapter.setRightAnswers(mRightAnswerForChinese);
				mQuestionResultAdapter.setItemCount(weekQuestionCount[mCurWeek-1]);
				mQuestionResultAdapter.setData(chineseQuestionList);
				list.setAdapter(mQuestionResultAdapter);
				mShowPage = PAGE_TESTRESULT;
				// list.setAdapter(new ArrayAdapter<String>(
				// SubjectStudyActivity.this,
				// android.R.layout.simple_list_item_1, mStrings2));
			}
		});

		btn_retry.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				llay_for_tab.setVisibility(View.VISIBLE);
				llay_for_result.setVisibility(View.GONE);
				llay_for_result_test.setVisibility(View.GONE);
				btn_smalltest.setBackgroundColor(color.cnn_white);
				btn_keypoint.setBackgroundColor(color.foreground1);
				btn_submit.setVisibility(View.VISIBLE);
				resetChineseQuestions();
				int pos=0;
				for (int i = 1; i < mCurWeek; i++) {
					pos += weekQuestionCount[i - 1];
				}
				mQuestionAdapter.setBasePos(pos);
				list.setAdapter(mQuestionAdapter);
				mShowPage = PAGE_SMALLTEST;
				// list.setAdapter(new ArrayAdapter<String>(
				// SubjectStudyActivity.this,
				// android.R.layout.simple_list_item_1, mStrings1));
			}
		});

		btn_toresult.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// Toast.makeText(SubjectStudy.this, "add your result to final",
				// Toast.LENGTH_SHORT).show();
				TestRecord test = new TestRecord(Subject.SUB_CHN, 3, mCurWeek, mScore,
						Calendar.getInstance(), mTimeTestEnd-mTimeTestStart, "Chinese small test");
				DataRecordUtil.addTestResult(SubjectStudyActivity.this, test);
				Intent intent = new Intent();
				intent.setClass(SubjectStudyActivity.this,
						TestResultActivity.class);
				startActivity(intent);
			}
		});

		img_to_prev.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if (mCurWeek > 1) {
					mCurWeek--;
					mHandler.sendMessage(mHandler
							.obtainMessage(MSG_WEEK_LEFT_CHANGED));
				}
			}
		});

		img_to_next.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				if (mCurWeek < weekCount) {
					mCurWeek++;
					mHandler.sendMessage(mHandler
							.obtainMessage(MSG_WEEK_RIGHT_CHANGED));
				}
			}
		});
	}

	/**
	 * A sample ListAdapter that presents content from arrays of speeches and
	 * text.
	 * 
	 */
	private class keypointListAdapter extends BaseAdapter {
		public keypointListAdapter() {
		}

		/**
		 * The number of items in the list is determined by the number of
		 * speeches in our array.
		 * 
		 * @see android.widget.ListAdapter#getCount()
		 */
		public int getCount() {
			return arrayKeypoints.length;
		}

		/**
		 * Since the data comes from an array, just returning the index is
		 * sufficent to get at the data. If we were using a more complex data
		 * structure, we would return whatever object represents one row in the
		 * list.
		 * 
		 * @see android.widget.ListAdapter#getItem(int)
		 */
		public Object getItem(int position) {
			return position;
		}

		/**
		 * Use the array index as a unique id.
		 * 
		 * @see android.widget.ListAdapter#getItemId(int)
		 */
		public long getItemId(int position) {
			return position;
		}

		/**
		 * Make a SpeechView to hold each row.
		 * 
		 * @see android.widget.ListAdapter#getView(int, android.view.View,
		 *      android.view.ViewGroup)
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			// ItemView sv;
			// if (convertView == null) {
			// sv = new ItemView(mContext, arrayKeypoints[position],
			// arrayDetails.get(mCurWeek*arrayKeypoints.length+position),
			// arrayExpanded[position]);
			// } else {
			// sv = (ItemView)convertView;
			// sv.setTitle(arrayKeypoints[position]);
			// sv.setDetail(arrayDetails.get(mCurWeek*arrayKeypoints.length+position));
			// sv.setExpanded(arrayExpanded[position]);
			// }
			//
			// return sv;
			// if(convertView )
			final KeyPointViewHolder holder;
			if (convertView == null) {
				convertView = mLayoutInflater.inflate(R.layout.item_keypoint,
						null);
				holder = new KeyPointViewHolder();
				LinearLayout llay_keypoint = (LinearLayout) convertView
						.findViewById(R.id.llay_keypoint);
				llay_keypoint.setLayoutParams(new LinearLayout.LayoutParams(
						mScreenWidth, LinearLayout.LayoutParams.WRAP_CONTENT));
				// holder.mKeypointIndex = (TextView) convertView
				// .findViewById(R.id.index_keypoint);
				holder.mKeypointText = (TextView) convertView
						.findViewById(R.id.text_keypoint);
				holder.mKeypointDetail = (TextView) convertView
						.findViewById(R.id.detail_keypoint);
				holder.mKeypointDetail.setVisibility(View.GONE);
				convertView.setTag(holder);
			} else {
				holder = (KeyPointViewHolder) convertView.getTag();
			}
			// holder.mKeypointIndex.setText(position + ". ");
			holder.mKeypointText.setText(arrayKeypoints[position]);
			holder.mKeypointDetail.setText(arrayDetails.get((mCurWeek - 1)
					* arrayKeypoints.length + position));
			holder.mKeypointDetail
					.setVisibility(arrayExpanded[position] ? View.VISIBLE
							: View.GONE);
			return convertView;
		}

		public void toggle(int position) {
			arrayExpanded[position] = !arrayExpanded[position];
			notifyDataSetChanged();
		}
	}

	private class KeyPointViewHolder {
		// TextView mKeypointIndex;
		TextView mKeypointText;
		TextView mKeypointDetail;
	}

	private class QuestionItem {
		private String questionGroupDes;
		private String questionDes;
		private String txtCha;
		private String txtChb;
		private String txtChc;
		private String txtChd;
		private int choice = -1;
		private boolean checked = false;
		private boolean isRight = false;
		public void setChoice(int choi) {
			choice = choi;
		}

		public int getChoice() {
			return choice;
		}

		public void setChecked(boolean flag) {
			checked = flag;
		}

		public boolean getChecked() {
			return checked;
		}
	}

	private class QuestionHolder {
		TextView txtGroupDes;
		TextView txtDes;
		RadioGroup rg;
		RadioButton rba;
		RadioButton rbb;
		RadioButton rbc;
		RadioButton rbd;
	}

	private class QuestionAdapter extends BaseAdapter {

		private Context mContext;
		private List<QuestionItem> mQuestions;
		private QuestionItem mItem;
		private int basePos = 0;
		public QuestionAdapter(Context con, List<QuestionItem> data) {
			mContext = con;
			mQuestions = data;
		}

		public void setBasePos(int pos) {
			basePos = pos;
		}
		
		public int getCount() {
			return weekQuestionCount[mCurWeek - 1];
		}

		public Object getItem(int position) {
			int pos = 0;
			for (int i = 1; i < mCurWeek; i++) {
				pos += weekQuestionCount[i - 1];
			}
			return mQuestions.get(pos);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
//			if (convertView == null) {
//				Log.e(TAG, "convertView == null");
//			}
			int pos = basePos;
			pos += position;
			mItem = mQuestions.get(pos);

			if (null == mItem) {
				return null;
			}
			final QuestionHolder holder;
			if (convertView != null) {
				holder = (QuestionHolder) convertView.getTag();
			} else {
				holder = new QuestionHolder();
				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.item_subject_test, null);
				holder.txtGroupDes = (TextView) convertView
						.findViewById(R.id.txt_question_group_des);
				holder.txtDes = (TextView) convertView
						.findViewById(R.id.txt_question_des);
				holder.rg = (RadioGroup) convertView
						.findViewById(R.id.rg_question_des);
				holder.rba = (RadioButton) convertView
						.findViewById(R.id.rb_cha);
				holder.rbb = (RadioButton) convertView
						.findViewById(R.id.rb_chb);
				holder.rbc = (RadioButton) convertView
						.findViewById(R.id.rb_chc);
				holder.rbd = (RadioButton) convertView
						.findViewById(R.id.rb_chd);
				convertView.setTag(holder);
			}
			if (TextUtils.isEmpty(mItem.questionGroupDes)) {
				holder.txtGroupDes.setVisibility(View.GONE);
			} else {
				holder.txtGroupDes.setVisibility(View.VISIBLE);
				holder.txtGroupDes.setText(mItem.questionGroupDes);
			}
			if (TextUtils.isEmpty(mItem.questionDes)) {
				holder.txtDes.setVisibility(View.GONE);
			} else {
				holder.txtDes.setVisibility(View.VISIBLE);
				holder.txtDes.setText(mItem.questionDes);
			}

			final int curPos = pos;
			if (!mQuestions.get(curPos).getChecked()) {
				holder.rg.clearCheck();
			} else {
				switch(mQuestions.get(curPos).getChoice()){
					case 0:
						holder.rba.setChecked(true);
						break;
					case 1:
						holder.rbb.setChecked(true);
						break;
					case 2:
						holder.rbc.setChecked(true);
						break;
					case 3:
						holder.rbd.setChecked(true);
						break;
				}
			}
			if (TextUtils.isEmpty(mItem.txtCha)) {
				holder.rba.setVisibility(View.GONE);
			} else {
				holder.rba.setVisibility(View.VISIBLE);
				holder.rba.setText(mItem.txtCha);
				holder.rba.setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {		
						mQuestions.get(curPos).setChoice(0);
						mQuestions.get(curPos).setChecked(true);
					}
				});
			}
			if (TextUtils.isEmpty(mItem.txtChb)) {
				holder.rbb.setVisibility(View.GONE);
			} else {
				holder.rbb.setVisibility(View.VISIBLE);
				holder.rbb.setText(mItem.txtChb);
				holder.rbb.setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {		
						mQuestions.get(curPos).setChoice(1);
						mQuestions.get(curPos).setChecked(true);
					}
				});
			}
			if (TextUtils.isEmpty(mItem.txtChc)) {
				holder.rbc.setVisibility(View.GONE);
			} else {
				holder.rbc.setVisibility(View.VISIBLE);
				holder.rbc.setText(mItem.txtChc);
				holder.rbc.setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {		
						mQuestions.get(curPos).setChoice(2);
						mQuestions.get(curPos).setChecked(true);
					}
				});
			}
			if (TextUtils.isEmpty(mItem.txtChd)) {
				holder.rbd.setVisibility(View.GONE);
			} else {
				holder.rbd.setVisibility(View.VISIBLE);
				holder.rbd.setText(mItem.txtChd);
				holder.rbd.setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {		
						mQuestions.get(curPos).setChoice(3);
						mQuestions.get(curPos).setChecked(true);
					}
				});
			}
			return convertView;
		}
	}

	private class QuestionResultHolder {
		TextView txtGroupDes;
		TextView txtDes;
		RadioGroup rg;
		RadioButton rba;
		RadioButton rbb;
		RadioButton rbc;
		RadioButton rbd;
		TextView msgResult;
		TextView rightAnswer;
		TextView answerResult;
		ImageView imgResult;
	}

	private class QuestionResultAdapter extends BaseAdapter {

		private Context mContext;
		private List<QuestionItem> mQuestions;
		private QuestionItem mItem;
		private int basePos = 0;
		private int mItemCount = -1; 
		private List<String> mRightAnswer;
		public QuestionResultAdapter(Context con, List<QuestionItem> data) {
			mContext = con;
			mQuestions = data;
		}

		public void setRightAnswers(List<String> answers){
			mRightAnswer = answers;
		}
		public void setBasePos(int pos){
			basePos = pos;
		}
		
		public void setData(List<QuestionItem> data){
			mQuestions = data;
		}
		
		public void setItemCount(int count){
			mItemCount = count;
		}
		
		public int getCount() {
			return mItemCount==-1?0:mItemCount;
		}

		public Object getItem(int position) {
			return mQuestions.get(basePos+position);
		}

		public long getItemId(int position) {
			return position+basePos;
		}

		/* (non-Javadoc)
		 * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			int pos = basePos;
			pos = pos+position;
			mItem = mQuestions.get(pos);
			if (null == mItem) {
				return null;
			}
			final QuestionResultHolder holder;
			if (convertView != null) {
				holder = (QuestionResultHolder) convertView.getTag();
			} else {
				holder = new QuestionResultHolder();
				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.item_subject_test_result, null);
				holder.txtGroupDes = (TextView) convertView
						.findViewById(R.id.txt_question_group_des);
				holder.txtDes = (TextView) convertView
						.findViewById(R.id.txt_question_des);
				holder.rg = (RadioGroup) convertView
						.findViewById(R.id.rg_question_des);
				holder.rba = (RadioButton) convertView
						.findViewById(R.id.rb_cha);
				holder.rbb = (RadioButton) convertView
						.findViewById(R.id.rb_chb);
				holder.rbc = (RadioButton) convertView
						.findViewById(R.id.rb_chc);
				holder.rbd = (RadioButton) convertView
						.findViewById(R.id.rb_chd);
				holder.msgResult = (TextView) convertView
						.findViewById(R.id.msg_right_answer);
				holder.rightAnswer = (TextView) convertView
						.findViewById(R.id.txt_right_answer);
				holder.answerResult=(TextView) convertView
						.findViewById(R.id.msg_answer_result);
				holder.imgResult = (ImageView) convertView
						.findViewById(R.id.img_result);
				convertView.setTag(holder);
			}
			//holder.rg.check(mItem.getChoice());
			
			if (TextUtils.isEmpty(mItem.questionGroupDes)) {
				holder.txtGroupDes.setVisibility(View.GONE);
			} else {
				holder.txtGroupDes.setVisibility(View.VISIBLE);
				holder.txtGroupDes.setText(mItem.questionGroupDes);
			}
			if (TextUtils.isEmpty(mItem.questionDes)) {
				holder.txtDes.setVisibility(View.GONE);
			} else {
				holder.txtDes.setVisibility(View.VISIBLE);
				holder.txtDes.setText(mItem.questionDes);
			}
			if (TextUtils.isEmpty(mItem.txtCha)) {
				holder.rba.setVisibility(View.GONE);
			} else {
				holder.rba.setVisibility(View.VISIBLE);
				holder.rba.setText(mItem.txtCha);
				holder.rba.setEnabled(false);
			}
			if (TextUtils.isEmpty(mItem.txtChb)) {
				holder.rbb.setVisibility(View.GONE);
			} else {
				holder.rbb.setVisibility(View.VISIBLE);
				holder.rbb.setText(mItem.txtChb);
				holder.rbb.setEnabled(false);
			}
			if (TextUtils.isEmpty(mItem.txtChc)) {
				holder.rbc.setVisibility(View.GONE);
			} else {
				holder.rbc.setVisibility(View.VISIBLE);
				holder.rbc.setText(mItem.txtChc);
				holder.rbc.setEnabled(false);
			}
			if (TextUtils.isEmpty(mItem.txtChd)) {
				holder.rbd.setVisibility(View.GONE);
			} else {
				holder.rbd.setVisibility(View.VISIBLE);
				holder.rbd.setText(mItem.txtChd);
				holder.rbd.setEnabled(false);
			}
			switch (mItem.getChoice()) {
				case 0: {
					holder.rba.setChecked(true);
					}
					break;
				case 1: {
					holder.rbb.setChecked(true);
					}
					break;
				case 2: {
					holder.rbc.setChecked(true);
					}
					break;
				case 3: {
					holder.rbd.setChecked(true);
					}
					break;
			}
			if(mItem.getChoice()==-1){
				holder.msgResult.setVisibility(View.GONE);
				holder.rightAnswer.setVisibility(View.GONE);
				holder.answerResult.setVisibility(View.GONE);
				holder.imgResult.setVisibility(View.GONE);
			}else{
				String rightAnswer = mRightAnswer.get(pos);
//				Log.e(TAG,"rightAnswer = "+rightAnswer+", pos="+pos);
				holder.msgResult.setVisibility(View.VISIBLE);
				holder.rightAnswer.setVisibility(View.VISIBLE);
				if(rightAnswer.equals("0")){
					holder.rightAnswer.setText("A");
				}else if(rightAnswer.equals("1")){
					holder.rightAnswer.setText("B");
				}
				else if(rightAnswer.equals("2")){
					holder.rightAnswer.setText("C");
				}
				else if(rightAnswer.equals("3")){
					holder.rightAnswer.setText("D");
				}
				holder.answerResult.setVisibility(View.VISIBLE);
				holder.imgResult.setVisibility(View.VISIBLE);
				if(mItem.isRight/*String.valueOf(mItem.getChoice()).equals(rightAnswer)*/){
					holder.answerResult.setText(R.string.msg_equal_right_answer);
					holder.imgResult.setImageResource(R.drawable.img_ok);
				}else{
					holder.answerResult.setText(R.string.msg_not_equal_right_answer);
					holder.imgResult.setImageResource(R.drawable.img_erro);
				}
			}
			return convertView;
		}
	}
}
